from fastapi import APIRouter, Request

from config.common import DM_DATABASE

# 创建一个路由分组
processing_api = APIRouter()


@processing_api.post(path="/xjxc/parse", tags=["巡检巡查文档解析API"])
async def xjxc_parse(request: Request):
    params_json = await request.json()
    doc_id = params_json["doc_id"]
    if doc_id is None:
        return {"code": 400, "success": False, "msg": "Invalid doc id"}

    doc = validate_doc_id(doc_id, request.app.store_handler)
    if not doc:
        return {"code": 400, "success": False, "msg": "Invalid doc id"}

    # 解析入库
    request.app.store_handler.executor.submit(request.app.store_handler.parse_and_store_xjxc_result,
                                              doc[0], doc[1], doc[2])
    return {"code": 200, "success": True, "data": {}}


@processing_api.post(path="/historyschdulingprocess/parse", tags=["历史调度过程文档解析API"])
async def history_scheduling_process_parse(request: Request):
    params_json = await request.json()
    doc_id = params_json["doc_id"]
    if doc_id is None:
        return {"code": 400, "success": False, "msg": "Invalid doc id"}

    doc = validate_doc_id(doc_id, request.app.store_handler)
    if not doc:
        return {"code": 400, "success": False, "msg": "Invalid doc id"}

    # 解析入库
    request.app.store_handler.executor.submit(
        request.app.store_handler.parse_and_store_history_scheduling_process_result,
        doc[0], doc[1], doc[2])
    return {"code": 200, "success": True, "data": {}}


def validate_doc_id(doc_id, handler):
    doc = handler.dm_client.execute_query_by_id(f"SELECT ID, NAME, PATH FROM {DM_DATABASE}.T_DOCUMENTS WHERE ID = ?",
                                                (doc_id,))
    if doc is not None:
        return doc
